// 假设这是从某个地方获取的 appSecret，实际中应通过安全方式获取
const appSecret = 'testAppSecret';
const appId = 'testAppId';

const bodyJson = {
    "username": "zhangsan",
    "password": "zhangsan123",
    "email": "zhangsan@dream.com",
    "address": "北京市朝阳区xxx小区"
};

init();

// 初始化操作
function init() {
    const json = JSON.stringify(bodyJson, null, 2);
    document.getElementById('bodyJson').value = json;
    initCommonHeader();
}

// 初始化公共请求头
function initCommonHeader() {
    document.getElementById('appId').value = appId;
    document.getElementById('appSecret').value = appSecret;
    document.getElementById('timestamp').value = Date.now().toString();
    document.getElementById('nonce').value = Math.random().toString(36).substring(2, 10);
    const params = {
        appId: appId,
        timestamp: document.getElementById('timestamp').value,
        nonce: document.getElementById('nonce').value,
        name: document.getElementById('paramName').value
    }
    document.getElementById('paramSign').value = sign(params);
    const body = document.getElementById('bodyJson').value;
    const parseBody = JSON.parse(body);
    // 收集参数
    const bodyParams = {
        ...parseBody,
        timestamp: document.getElementById('timestamp').value,
        nonce: document.getElementById('nonce').value,
        name: document.getElementById('paramName').value
    };
    document.getElementById('bodySign').value = sign(bodyParams);
}

// 刷新sign签名MD5值
function flushSign() {
    const appId = document.getElementById('appId').value;
    const timestamp = document.getElementById('timestamp').value;
    const nonce = document.getElementById('nonce').value;
    // 收集参数
    const params = {
        appId: appId,
        name: document.getElementById('paramName').value,
        nonce: nonce,
        timestamp: timestamp
    };

    // 生成 MD5 签名
    const md5 = sign(params);
    document.getElementById('paramSign').value = md5;

    const body = document.getElementById('bodyJson').value;
    const parseBody = JSON.parse(body);
    // 收集参数
    const bodyParams = {
        ...parseBody,
        appId: appId,
        nonce: nonce,
        timestamp: timestamp
    };
    const bodyMd5 = sign(bodyParams);
    document.getElementById('bodySign').value = bodyMd5;
}

function submitParam(flag) {
    const timestamp = flag ? document.getElementById('timestamp').value : Date.now().toString();
    const nonce = flag ? document.getElementById('nonce').value : Math.random().toString(36).substring(2, 10);

    // 收集参数
    const params = {
        appId: document.getElementById('appId').value,
        name: document.getElementById('paramName').value,
        nonce: nonce,
        timestamp: timestamp
    };

    // 生成 MD5 签名
    const md5 = flag ? document.getElementById('paramSign').value : sign(params);

    // 构建 RequestParam 形式的参数
    const requestParams = new URLSearchParams({
        name: document.getElementById('paramName').value
    }).toString();

    // 拼接 URL 和参数
    const url = `/demo/submitParam?${requestParams}`;

    fetch(url, {
        method: 'POST',
        headers: {
            // 这里不需要设置 Content-Type 为 application/json
            'appId': document.getElementById('appId').value,
            'timestamp': timestamp,
            'nonce': nonce,
            'sign': md5
        }
    })
        .then(response => response.json())
        .then(data => {
            const json = JSON.stringify(data, null, 2);
            document.getElementById('result').value = json;
        })
        .catch(err => console.log(err));
}

function submitBody(flag) {
    const timestamp = flag ? document.getElementById('timestamp').value : Date.now().toString();
    const nonce = flag ? document.getElementById('nonce').value : Math.random().toString(36).substring(2, 10);

    const body = document.getElementById('bodyJson').value;
    const parseBody = JSON.parse(body);
    // 收集参数
    const params = {
        ...parseBody,
        appId: document.getElementById('appId').value,
        nonce: nonce,
        timestamp: timestamp
    };
    const md5 = flag ? document.getElementById('bodySign').value : sign(params);

    fetch('/demo/submitBody', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'appId': document.getElementById('appId').value,
            'timestamp': timestamp,
            'nonce': nonce,
            'sign': md5
        },
        body: JSON.stringify(parseBody)
    })
        .then(response => response.json())
        .then(data => {
            const json = JSON.stringify(data, null, 2);
            document.getElementById('result').value = json;
        })
        .catch(err => console.log(err));
}

// 签名
function sign(params) {
    // 对参数进行排序
    const sortedParams = Object.keys(params).sort().reduce((obj, key) => {
        obj[key] = params[key];
        return obj;
    }, {});

    // 拼接参数
    let paramStr = '';
    for (const key in sortedParams) {
        if (sortedParams.hasOwnProperty(key)) {
            paramStr += `${key}=${sortedParams[key]}&`;
        }
    }
    const appSecret = document.getElementById('appSecret').value;
    paramStr += `appSecret=${appSecret}`;

    // 生成 MD5 签名
    const sign = CryptoJS.MD5(paramStr).toString();
    return sign;
}